package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.RideTestDao;
import com.rk.kbk.dao.TestDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.RideTest;
import com.rk.kbk.model.Test;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.*;

/**
 * @TestController
 * @测试题Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/test")
public class TestController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private TestDao testDao;
    @Autowired
    private RideTestDao rideTestDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改测试题
     * @param test
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addTest",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateTest(@RequestBody Test test){
        log.debug("添加测试题");
        Long id=test.getId();
        if(id==null){
            testDao.save(test);
        }else {
            Test test1=testDao.findOne(id);
            test1.setIsMore(test.getIsMore());
            test1.setRightOption(test.getRightOption());
            test1.setSelectOption(test.getSelectOption());
            test1.setTitle(test.getTitle());
            test1.setScore(test.getScore());
            testDao.save(test1);
        }

        return JsonResp.ok();
    }

    /**
     * @批量添加/修改测试题
     * @param tests
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeTest",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeTest(@RequestBody List<Test> tests){
        log.debug("批量添加/修改测试题");
        testDao.save(tests);
        return JsonResp.ok();
    }



    /**
     * @考试题列表
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getTestList",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getTestList(){
        log.debug("考试题列表");
        List<Test> testList=testDao.findAll();
        List<Map> allTestList=new ArrayList<>();
        int i=0,y=testList.size();
        for(;i<y;i++){
            Test test=testList.get(i);
            Map map=new HashMap();
            map.put("testTitle",test.getTitle());
            map.put("testId",test.getId());
            map.put("isMore",test.getIsMore());
            map.put("score",test.getScore());//本题分数
            String selectOptionArr []=test.getSelectOption().split(",");
            String rightOptionArr []=test.getRightOption().split(",");
            List<String> selectOptionList= Arrays.asList(selectOptionArr);
            List<String> rightOptionList= Arrays.asList(rightOptionArr);
            map.put("selectOptionList",selectOptionList);
            map.put("rightOptionList",rightOptionList);
            allTestList.add(map);
        }
        return JsonResp.ok(allTestList);
    }





    /**
     * @获取试题列表（后台）
     * @param pageSize
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getTestListWithPage",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getTestListWithPage( Integer type,Integer pageNum, Integer pageSize) {
        log.debug("获取测试题详情-ByTestId");
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = testDao.findAll( 		  //条件分页
                (root, criteriaQuery, cb) -> {
                    Predicate predicate = cb.conjunction();
                    List<Expression<Boolean>> expressions = predicate.getExpressions();
                    if(type!=-1){
                        expressions.add(cb.equal(root.get("isMore"), type));
                    }
                    return predicate;
                }, pageable);

        return JsonResp.ok(new PageDto(page));
    }









    /**
     * @获取测试题详情-ByTestId
     * @param testId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/testDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findTestDetailsByTestId(Long testId) {
        log.debug("获取测试题详情-ByTestId");
        return JsonResp.ok(testDao.findOne(testId));
    }

    /**
     * @分页查询测试题(jpa方式)
     * @param test 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageTestJpa(@RequestBody(required = false) Test test, Integer pageNum, Integer pageSize) {
        log.debug("分页查询测试题(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == test) {
            page = testDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  test.getUserName();
            page = testDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<Test> content = page.getContent();
//        for (Test test1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除测试题-one(永久)
     * @param testId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteTest",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteTestOne(String testId) {
        log.debug("删除测试题-one(永久)");
        Test test =testDao.findOne(Long.valueOf(testId));
        List<RideTest> tests = rideTestDao.findByTest(test);
        rideTestDao.delete(tests);
        testDao.delete(test);
        return JsonResp.ok();
    }

    /**
     * @批量删除测试题(永久)
     * @param tests
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeTest",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeTest(@RequestBody List<Test> tests) {
        log.debug("批量删除测试题(永久)");
        testDao.delete(tests);
        return JsonResp.ok();
    }

    /**
     * @根据id获取试题详情
     * @param testId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getTestById",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getTestById(Long testId){
        log.debug("根据id获取试题详情");
        Test test=testDao.findOne(testId);
        return JsonResp.ok(test);
    }

}
